<script setup>
//获取用户信息
import httpInstance from "@/axios/index";

import {onMounted, ref} from "vue";
import {Plus, Refresh} from "@element-plus/icons-vue";
import {ElMessage, ElMessageBox} from "element-plus";
import qs from "qs";

//用户仓库
import { useUserStore } from "@/stores/user.js";
const userStore = useUserStore();

const subType = ref("")
const fromData = ref({
  id: -1,
  roleId: 1,
  departmentId: 1,
  account: "",
  password: "",
  realName: "",
  status: 1,
  remarks: "",
  avatarUrl: ""
})
const tableData = ref()

//分页信息
const page = ref({
  pageNo: 1,
  pageSize: 5,
  pageTotal: 0
})
const pageSize = ref([5, 10, 15, 20])

//获取信息
const query = ref({
  roleId: -1,
  account: ""
})

const reset = () => {
  query.value.roleId = -1
  query.value.account = ""
  getUserInfo()
}

const getUserInfo = () => {
  //拼接请求地址
  let url = "/user/getUserList?pageNo=" + page.value.pageNo +
      "&pageSize=" + page.value.pageSize +
      "&roleId=" + query.value.roleId +
      "&account=" + query.value.account
  httpInstance.get(url).then(responseData => {
    if (responseData.code === 200) {
      tableData.value = responseData.data
      page.value.pageNo = responseData.data.current
      page.value.pageTotal = responseData.data.total
    }
  })
}

//获取角色组信息
const role = ref()
const getRoleInfo = () => {
  httpInstance.get('/role/getRole').then(responseData => {
    if (responseData.code === 200) {
      role.value = responseData.data
    }
  })
}
onMounted(getRoleInfo)

//获取科室信息
const department = ref()
const getDepartmentInfo = () => {
  httpInstance.get('/dep/getDepList').then(responseData => {
    if (responseData.code === 200) {
      department.value = responseData.data
    }
  })
}
onMounted(getDepartmentInfo)

//根据id获取账号信息
const getRoleById = (id) => {
  httpInstance.get('/user/getUserById?id=' + id).then(responseData => {
    fromData.value.id = responseData.data.id
    fromData.value.roleId = responseData.data.roleId
    fromData.value.departmentId = responseData.data.departmentId
    fromData.value.account = responseData.data.account
    fromData.value.realName = responseData.data.realName
    fromData.value.status = responseData.data.status
    fromData.value.remarks = responseData.data.remarks
    fromData.value.avatarUrl = responseData.data.avatarUrl
  })
}

//删除数据
const deleteInfo = (id) => {
  ElMessageBox.confirm('此操作将永久删除该数据, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    httpInstance.delete('/user/deleteUser?id=' + id).then(responseData => {
      if (responseData.code === 200) {
        ElMessage.success('删除成功')
        getUserInfo()
      }
    })
  }).catch(() => {

  })
}

//新增数据
const insertInfo = () => {
  httpInstance.post('/user/addUser', qs.stringify(fromData.value)).then(responseData => {
    if (responseData.code === 200) {
      ElMessage.success('新增成功')
      getUserInfo()
      handleClose()
    }
  }).catch(() => {

  })
}

//修改数据
const updateInfo = () => {
  httpInstance.put('/user/updateUser', qs.stringify(fromData.value)).then(responseData => {
    if (responseData.code === 200) {
      ElMessage.success('修改成功')
      if(fromData.value.id === userStore.userInfo.id){
        userStore.userInfo.avatarUrl = fromData.value.avatarUrl
      }
      getUserInfo()
      handleClose()
    }
  }).catch(() => {

  })
}

const handleClose = (done) => {
  if (loading.value) {
    return
  }
  dialog.value = false
  fromData.value = {
    id: -1,
    roleId: 1,
    departmentId: 1,
    account: "",
    password: "",
    realName: "",
    status: 1,
    remarks: "",
    avatarUrl: ""
  }
}

//判断账号是否存在
const checkAccount = () => {
  httpInstance.get('/user/isExist?account=' + fromData.value.account).then(responseData => {
    if (responseData.code === 200) {
      ElMessage.success('账号可用')
      return true;
    } else {
      ElMessage.error('账号不可用')
      return false;
    }
  })
}

const dialog = ref(false)
const loading = ref(false)
const fangXiang = ref("ltr")

//数据操作
const onClick = () => {
  if (subType.value === "Insert") {
    if (checkAccount) {
      insertInfo()
    }
  } else {
    updateInfo()
  }
}

onMounted(getUserInfo)

//图片上传部分
// 文件上传URL，从axios的配置项中取到统一前缀
const uploadUrl = 'http://localhost:8080/api/file/upload'
const uploadHeader = ref({
  // 文件上传请求头，后端接口是需要验证是否登录的
  Authorization: localStorage.getItem("Authorization")
})

const handleAvatarSuccess = (res, file) => {
  // res：上传成功后服务器返回的数据
  fromData.value.avatarUrl = res.data.path;
}
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG和PNG 格式');
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB');
  }
  return isJPG && isLt2M;
}

</script>

<template>
  <el-row>
    <el-drawer
        v-model="dialog"
        title="数据操作"
        :direction="fangXiang"
        :before-close="handleClose"
        class="demo-drawer"
    >
      <div class="demo-drawer__content">
        <el-form

            label-position="top"
            label-width="auto"
            :model="fromData"
            style="max-width: 600px"
        >
          <el-form-item>
            <el-select
                v-model="fromData.roleId"
                style="max-width: 600px"
            >
              <el-option
                  v-for="item in role"
                  :key="item.id"
                  :label="item.roleName"
                  :value="item.id"
              />
              <template #prefix>所属角色组:</template>
            </el-select>
          </el-form-item>
          <el-form-item v-if="fromData.roleId === 3">
            <el-select
                v-model="fromData.departmentId"
                style="max-width: 600px"
            >
              <el-option
                  v-for="item in department"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              />
              <template #prefix>所属门诊科室:</template>
            </el-select>
          </el-form-item>
          <el-form-item v-if="subType === 'Update'">
            <el-input type="text" disabled value="点击下方按钮上传头像">
              <template slot="prepend">账户头像</template>
            </el-input>
            <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :headers="uploadHeader"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
            >
              <img v-if="fromData.avatarUrl" :src="fromData.avatarUrl" class="avatar" alt=""/>
              <el-icon v-else class="avatar-uploader-icon">
                <Plus/>
              </el-icon>
            </el-upload>

          </el-form-item>
          <el-form-item>
            <el-input
                :disabled="subType === 'Update'"
                v-model="fromData.account"
                placeholder="请输入账号"
                style="max-width: 600px"
            >
              <template #prepend>账户账号</template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-input
                type="password"
                v-model="fromData.password"
                :placeholder="subType=='Update' ? '非必要请不要修改密码' : '请输入密码'"
                style="max-width: 600px"
            >
              <template #prepend>账户密码</template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-input
                v-model="fromData.realName"
                placeholder="请输入姓名"
                style="max-width: 600px"
            >
              <template #prepend>真实姓名</template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-select
                :disabled="fromData.roleId === 1"
                v-model="fromData.status"
                style="max-width: 600px"
            >
              <el-option
                  v-for="item in [{label: '正常', value: 1}, {label: '禁用', value: 0}]"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
              <template #prefix>状态</template>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input
                v-model="fromData.remarks"
                placeholder="请输入备注"
                style="max-width: 600px"
            >
              <template #prepend>备注</template>
            </el-input>
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="handleClose">清空</el-button>
          <el-button type="primary" :loading="loading" @click="onClick">
            {{ loading ? '提交中...' : '提交' }}
          </el-button>
        </div>
      </div>
    </el-drawer>
    <el-col :span="24">
      <el-row>
        <el-col :span="24">
          <el-card>
            <div slot="header" class="clearfix">
              <el-form :inline="true">
                <el-form-item label="所属角色组:">
                  <el-select
                      v-model="query.roleId"
                      style="width: 150px"
                  >
                    <el-option
                        label="全部"
                        :value="-1"
                    />
                    <el-option
                        v-for="item in role"
                        :key="item.id"
                        :label="item.roleName"
                        :value="item.id"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="账户账号:">
                  <el-input
                      v-model="query.account"
                      placeholder="请输入账户账号"
                      style="max-width: 200px"
                  />
                </el-form-item>
              </el-form>
            </div>
            <div>
              <el-button color="#409EFF" style="color: white" @click="getUserInfo">
                <el-icon>
                  <Search/>
                </el-icon>
                <span>搜索</span>
              </el-button>
              <el-button color="#fff" dark="dark" @click="reset">
                <el-icon>
                  <Refresh/>
                </el-icon>
                <span>重置</span>
              </el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-card>
            <div slot="header" class="clearfix">
              <span style="display: flex;
                                align-items: center;
                                justify-content: space-between;
                                width: 100%;">
                    <el-button color="#409EFF" style="color: white"
                               @click="dialog = true;fangXiang = 'ltr';subType = 'Insert';">
                      <el-icon><Plus/></el-icon>
                      <span>新增</span>
                    </el-button>
                  </span>
            </div>
            <div class="text item">
              <el-table border :data="tableData?.records" height="360px" style="width: 100%;min-height: 340px">
                <el-table-column prop="id" label="id" width="50" header-align="center" align="center"/>
                <el-table-column prop="account" label="账户账号" width="100" header-align="center" align="center"/>
                <el-table-column label="所属角色组" width="110" header-align="center" align="center">
                  <template #default="info">
                    <el-tag v-if="info.row.sysRole.roleName" type="success">{{ info.row.sysRole.roleName }}</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="realName" label="真实姓名" width="120" header-align="center" align="center"/>
                <el-table-column label="用户状态" width="120" header-align="center" align="center">
                  <template #default="info">
                    <el-tag v-if="info.row.status == 1" type="success">正常</el-tag>
                    <el-tag v-else type="danger">禁用</el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="remarks" label="账户备注" header-align="center" align="center"/>
                <el-table-column fixed="right" label="操作" width="160" header-align="center" align="center">
                  <template #default="info">
                    <div style="display: flex;">
                      <el-button size="small" color="#019768"
                                 @click="getRoleById(info.row.id);dialog = true;;subType = 'Update';fangXiang = 'rtl';fromData.id = info.row.id">
                        <el-icon>
                          <Plus/>
                        </el-icon>
                        <span>修改</span>
                      </el-button>
                      <el-button size="small" color="#F43D5E" v-bind:disabled="info.row.sysRole.isSuper == 1"
                                 @click="deleteInfo(info.row.id)">
                        <el-icon>
                          <Plus/>
                        </el-icon>
                        <span>删除</span>
                      </el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div slot="footer" class="card-footer">
              <el-pagination
                  v-model:current-page="page.pageNo"
                  v-model:page-size="page.pageSize"
                  :page-sizes="pageSize"
                  background
                  layout="sizes, prev, pager, next"
                  :total="page.pageTotal"
                  @size-change="getUserInfo"
                  @current-change="getUserInfo"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-col>
  </el-row>
</template>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.card-footer {
  display: flex;
  justify-content: flex-end;
}

.el-card {
  margin: 10px;
}

.NoData {
  display: flex;
  justify-content: center;
  flex-direction: column;
  font-size: 14px;
  color: #a5a5a5
}
</style>